<template>
  <div class="upload">
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :http-request="uploadFn"
      :on-remove="handleRemove"
      :file-list="fileList"
      :limit="limit"
      :class="{disable: fileList.length=== limit}"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="percentShow" :text-inside="true" :stroke-width="18" :percentage="percent" status="success" />
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDHZ0GG0UjiidQ0MVR9cqtjLnzxe8NM6Zm',
  SecretKey: '5uTntkLErFp8C0anulMhRzNXS8ZlgOs6'
})
export default {
  props: { // 父传子，父组件指定可以上传的图片数量
    number: {
      type: [Number, String],
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      percent: 0,
      percentShow: false,
      limit: this.number
    }
  },
  methods: {
    uploadFn(file) {
      this.percentShow = true
      cos.putObject({
        Bucket: 'szproject-1312551920', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: Date.now().toString(), /* 必须 */
        StorageClass: 'STANDARD',
        Body: file.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        console.log(47, data.Location)
        if (err) {
          return this.$message.error('请重新上传')
        }
        this.fileList.push({ url: 'http://' + data.Location })
        const timeID = setTimeout(() => {
          this.percentShow = false
          clearTimeout(timeID)
        }, 1000)
      })
    },
    handleRemove(file) {
      this.percent = 0
      const index = this.fileList.findIndex(item => item.url === file.url)
      this.fileList.splice(index, 1)
    }
  }
}
</script>

<style lang="scss">
.disable{
    .el-upload--picture-card{
    display: none;
}
}
.upload{
    display: inline-block;
    .el-progress{
        width: 100%;
    }
}
</style>

